package com.cn.zpark.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackageName: com.cn.zpark.filter
 * @ClassName: FilterDemo02
 * @Description:
 * @author: RZS
 * @date: 2022/4/18  14:14
 */
public class FilterDemo02 implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        System.out.println("FilterDemo02初始化成功");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 将请求、响应对象做类型转换操作
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 设置请求缓冲区编码，响应格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        // 获取初始化参数
        String username = filterConfig.getInitParameter("username");
        // 获取请求参数
        String uname = req.getParameter("uname");
        if(username.equals(uname)){
            // 提示不允许访问
            resp.getWriter().println("<h1>"+uname+"禁止访问</h1>");
        }else{
            // 转给下一个filter或者web资源
            chain.doFilter(req, resp);
        }


    }

    @Override
    public void destroy() {
        System.out.println("FilterDemo02被销毁");
    }
}
